﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace NAntMenu.Core
{
    public class NAntBuildFile
    {
        private string filePath;
        public string FilePath
        {
            get
            {
                return filePath;
            }
            set
            {
                filePath = value;
                ParseNAntBuildFile();
            }
        }

        public NAntBuildFileTarget DefaultTarget { get; set; }
        public NAntBuildFileTargets Targets { get; set; }

        public NAntBuildFile()
        {
            this.Targets = new NAntBuildFileTargets();
        }

        public NAntBuildFile(string filePath)
            : this()
        {
            this.FilePath = filePath;
        }

        private void ParseNAntBuildFile()
        {
            XmlDocument file = new XmlDocument();
            file.Load(this.FilePath);
            if (file.DocumentElement == null || (string.Compare(file.DocumentElement.Name, "project", StringComparison.OrdinalIgnoreCase) != 0) )
            {
                throw new Exception(string.Format("\"{0}\" is not a valid NAnt build file.", this.FilePath));
            }

            string defaultAttributeName = "default";

            if (file.DocumentElement.HasAttribute(defaultAttributeName))
            {
                this.DefaultTarget = new NAntBuildFileTarget();
                this.DefaultTarget.Name = file.DocumentElement.GetAttribute(defaultAttributeName);
                this.DefaultTarget.Description = "Build the default target";
            }

            XmlNodeList targets = file.SelectNodes("/project/target");
            foreach (XmlNode target in targets)
            {
                NAntBuildFileTarget nantBuildFileTarget = new NAntBuildFileTarget();

                XmlAttribute nameAttribute = target.Attributes["name"];
                if (nameAttribute == null)
                {
                    throw new Exception(string.Format("\"{0}\" is not a valid NAnt build file.", this.FilePath));
                }

                string targetName = nameAttribute.Value;

                nantBuildFileTarget.Name = targetName;

                XmlAttribute descriptionAttribute = target.Attributes["description"];
                if (descriptionAttribute == null)
                {
                    nantBuildFileTarget.Description = "Execute Target \"" + targetName + "\" on the file with NAnt";
                }
                else
                {
                    nantBuildFileTarget.Description = descriptionAttribute.Value;
                }

                this.Targets.Add(nantBuildFileTarget);
            }
        }
    }
}
